# 给定一个包含 n 个整数的数组 nums 和一个目标值 target，判断 nums 中是否存在四个元素 a，b，c 和 d ，
# 使得 a + b + c + d 的值与 target 相等？找出所有满足条件且不重复的四元组。


def fourSum(nums, target):
    nums.sort()
    len_sums, res = len(nums), []
    for i in range(0, len_sums - 3):
        if i != 0 and nums[i] == nums[i - 1]:
            continue
        mid_nums = nums[i+1:]
        mid_tar = target - nums[i]
        mid_res = threeSum(mid_nums, mid_tar)
        for j in mid_res:
            j.insert(0, nums[i])
        res.extend(mid_res)
    return res


def threeSum(nums, target):
    len_sums, res = len(nums), []
    for i in range(0, len_sums - 2):
        if i != 0 and nums[i] == nums[i - 1]:
            continue
        j, h = i + 1, len_sums - 1
        while j < h:
            num_sum = nums[i] + nums[j] + nums[h]
            if num_sum == target:
                res.append([nums[i], nums[j], nums[h]])
                j += 1
                h -= 1
                while j < h and nums[j] == nums[j - 1]:
                    j += 1
                while h > j and nums[h] == nums[h + 1]:
                    h -= 1
            elif num_sum < target:
                j += 1
            else:
                h -= 1
    return res


print(fourSum([1, 0, -1, 0, -2, 2], 0))
